package com.example.fairplay.newfpregistration.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.camera.CameraInterface;
import com.example.fairplay.newfpregistration.camera.FacePicInterface;
import com.example.fairplay.newfpregistration.camera.FragmentCamera;
import com.example.mylibrary.MyApp;
import com.example.mylibrary.config.Config;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DataDao;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.util.ActivityCollector;
import com.example.mylibrary.util.ImageUtil;
import com.example.mylibrary.util.Logger;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.aratek.facelib.AraFaceAuthLib;
import cn.com.aratek.fp.FingerprintScanner;
import cn.com.aratek.idcard.IDCard;
import cn.com.aratek.idcard.IDCardReader;
import cn.com.aratek.util.Result;



public class TransitionActivity extends AppCompatActivity implements FacePicInterface {
    private static final int MAX_VERIFY_COUNT = 5;
    private static final String PATH = Environment
            .getExternalStorageDirectory() + "/sdcard/FP-KTA2203/Photo/";
    private static final int MSG_FP_RESULT = 0;
    private static final int MSG_SHOW_INFO = 1;
    private static final int MSG_CARD_INFO = 2;
    private static final int MSG_SHOW_PROGRESS_DIALOG = 3;
    private static final int MSG_DISMISS_PROGRESS_DIALOG = 4;
    private static final int MSG_FACE_RESULT = 8;
    public static Context mContext;
    private boolean isReading = true;
    private IDCardReader mReader;
    private TransitionActivity.ReadThread mReadThread;
    private IDCard idCard;
    private Bitmap Sbitmap = null;
    private byte[] cardData = null;
    private AraFaceAuthLib araFaceAuthLib;
    private ProgressDialog mProgressDialog;
    private FingerprintScanner mScanner;
    private StudentInfo studentInfo;
    private MyApp app;
    private Logger logger;
    private List<StudentInfo> studentInfos;
    private List<StudentInfo> studentInfoss;
    //android.support.v4.app.Fragment使用  getSupportFragmentManager();
    private FragmentManager manager = getSupportFragmentManager();
    private int FPResult = -99;
    private File fic;
    private File fss;
    private ExecutorService cachedThreadPool;
    private FragmentCamera fragment;
    @Bind(R.id.ed_transition)
    EditText ed_transition;

    private String cardNum;
    private byte[] snapshotFeature;
    private List<StudentInfo> studentInfoAll;
    private ArrayList<ByteImg> bytes;
    private ByteImg byteImg;
    private List<ByteImg> imgList;
    private String stuCode;
    private RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transition);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initDatas();

        //条码枪 扫描自动跳转页面
        ed_transition.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // do something
                }
                manualQuery();
                return true;
            }
        });
        mContext = this;
    }
    // public void PhotoAll(){
//        bytes=new ArrayList<>();
//        //根据所有考生考号获取考生图片
//        studentInfoAll = new ArrayList<>();
//        studentInfoAll = DataDao.queryAll();
//        for (int i = 0; i< studentInfoAll.size(); i++) {
//            studentInfo = studentInfoAll.get(i);
//            String filepath = "/sdcard/zhongshan/img/";
//            File file = new File(filepath+ studentInfo.getStudenCode()+".jpg");
//            if (file !=null){
//                Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
//                //将图片转换成byte[]
//                cardData = araFaceAuthLib.getFeature(bm);
//                bytes.add(cardData);
//            }
//        }
  //  }


    public FragmentCamera getFragment() {
        return fragment;
    }

    @OnClick({R.id.btn_query,R.id.btn_scanner})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_query:
                manualQuery();
                break;
            case R.id.btn_scanner:
                //扫描二维码
                new IntentIntegrator(this)
                        .setOrientationLocked(false)
                        .setCaptureActivity(ScannerActivity.class) // 设置自定义的activity是ScanActivity
                        .initiateScan(); // 初始化扫描

                break;
        }
    }


    //二维码
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(intentResult != null) {
            if(intentResult.getContents() == null) {
                Toast.makeText(this,"内容为空",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this,"扫描成功",Toast.LENGTH_LONG).show();
                // ScanResult 为 获取到的字符串
                String scanResult = intentResult.getContents();
                Intent intent = new Intent(TransitionActivity.this,MainCheckActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("scanner",scanResult);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();

                Log.e("Scanner:",scanResult);
            }
        } else {
            super.onActivityResult(requestCode,resultCode,data);
        }
    }




    private void initDatas() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mReader = IDCardReader.getInstance(this);
        araFaceAuthLib = MainMenu.getAraFaceAuthLib();
        cachedThreadPool = Executors.newCachedThreadPool();
        mScanner = FingerprintScanner.getInstance(this);
        studentInfo = new StudentInfo();
        app = MyApp.getInstance();
        creatFile();
        //打开设备

    }

    private void creatFile() {
        fic = new File(PATH + "IDCard");
        if (!fic.exists()) {
            try {
                fic.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        fss = new File(PATH + "Snapshot");
        if (!fss.exists()) {
            try {
                fss.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //打开身份证设备
    private void openDevice() {
        new Thread() {
            @Override
            public void run() {
                int error;
                showProgressDialog(getString(R.string.loading), getString(R.string.preparing_device));
                if ((error = mReader.powerOn()) != IDCardReader.RESULT_OK) {
                    showInfoToast(getString(R.string.id_card_reader_power_on_failed));
                    dismissProgressDialog();
                    return;
                }
                if ((error = mReader.open()) != IDCardReader.RESULT_OK) {
                    showInfoToast(getString(R.string.id_card_reader_open_failed));
                    dismissProgressDialog();
                    return;
                }
                dismissProgressDialog();
                showInfoToast(getString(R.string.device_open_success));
                readCard();
            }
        }.start();
    }

    //显示对话框
    private void showProgressDialog(String title, String message) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_PROGRESS_DIALOG,
                new String[]{title, message}));
    }

    private void dismissProgressDialog() {
        mHandler.sendMessage(mHandler
                .obtainMessage(MSG_DISMISS_PROGRESS_DIALOG));
    }

    private void readCard() {
        isReading = true;
        if (mReadThread == null) {
            mReadThread = new TransitionActivity.ReadThread();
            mReadThread.start();
        }
    }

    private void stopReading() {
        isReading = false;
        mReadThread = null;

    }
    //将状态再次 进行判断
    @Override
    protected void onResume() {
        super.onResume();
        if (MyApp.mACache.getAsString("人脸认证") != null) {
            //开启
            if (Boolean.valueOf(MyApp.mACache.getAsString("人脸认证"))) {
                //开启状态
                faceResult();
            } else {
                //关闭状态
            }
        }
        if (MyApp.mACache1.getAsString("指纹认证") != null) {
            //开启
            if (Boolean.valueOf(MyApp.mACache1.getAsString("指纹认证"))) {
                //开启状态
                openDevice();
            } else {
                //关闭状态
            }
        }
    }
    //跳转人脸页面
    private void faceResult(){
        bytes=new ArrayList<>();
        byteImg = new ByteImg();
        imgList = new ArrayList<>();
        imgList = DataDao.imgAll();
        for (int i = 0; i< imgList.size(); i++){
            ByteImg byteImg=new ByteImg();
            byteImg = imgList.get(i);
            if(byteImg.getByteImg() !=null){
                cardData = byteImg.getByteImg();
                byteImg.setByteImg(cardData);
                byteImg.setImgId(imgList.get(i).getImgId());
                bytes.add(byteImg);
            }
        }

        fragment = new FragmentCamera();
        //fragment.setBytes(bytes);
        //fragment.setIDCardData(cardData);

        CameraInterface.setVerifyCount(MAX_VERIFY_COUNT);
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.content1, fragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }
    //返回键按钮操作
        @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(this,MainMenu.class));
        ActivityCollector.removeActivity(this);
            finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDevice();
    }

    //关闭设备
    private void closeDevice() {
        new Thread() {
            @Override
            public void run() {
                int error;
                isReading = false;
                mReadThread = null;
                if ((error = mReader.close()) != IDCardReader.RESULT_OK) {
                //   showInfoToast(getString(R.string.id_card_reader_close_failed));
                    dismissProgressDialog();
                    return;
                }
                if ((error = mReader.powerOff()) != IDCardReader.RESULT_OK) {
                  //  showInfoToast(getString(R.string.id_card_reader_power_off_failed));
                    dismissProgressDialog();
                    return;
                }

                showInfoToast(getString(R.string.device_close_success));
            }
        }.start();
    }

    private void clearFeature() {
        cardData = null;
        Sbitmap = null;

    }

    private void showInfoToast(String info) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_INFO, info));
    }

    //读取身份证
    private class ReadThread extends Thread {
        public void run() {
            Result res;
            do {
                res = mReader.read();
            } while (res.error != IDCardReader.RESULT_OK && isReading == true);
            if (res.error == IDCardReader.RESULT_OK) {
                showInfoToast(getString(R.string.id_card_read_success));
               mHandler.sendMessage(mHandler.obtainMessage(MSG_CARD_INFO, (IDCard) res.data));
                idCard = (IDCard) res.data;
                Log.d("idCard",idCard.toString());
                final Result temp = res;
                clearFeature();
                cardNum = idCard.getNumber();
                //将查询到的数据给数组
                stopReading();
            }else {

            }
        }

    }

    @Override
    public void fromPic(int requestCode, int resultCode, Intent data) {
        if (requestCode == 222){
            if (resultCode ==1){
                float score = data.getFloatExtra("score",0);
                snapshotFeature = data.getByteArrayExtra("snapshotFeature");
                stuCode = data.getStringExtra("stuCode");
                saveData( snapshotFeature,score, stuCode);
            }else {
                readCard();

            }
        }
    }

    private void saveData(final byte[] snapshotFeature, final float score, final String stuCode) {

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                setSnapshotFeature(snapshotFeature,score,stuCode);
            }


        });

    }
    private void setSnapshotFeature(byte[] snapshotFeature, float score,String stuCode) {
        final Bitmap b = ImageUtil.getRotateBitmap(BitmapFactory.decodeByteArray(snapshotFeature,0,snapshotFeature.length), Config.displayOrientation);
        Sbitmap = b;
        String res = String.valueOf(score);
        mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_RESULT, res));
        TransitionActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });

    }

    //根据EditText获取值   判断
    public void manualQuery() {
        final String idinfo = ed_transition.getText().toString().trim();
        studentInfoss = DataDao.queryInfo(idinfo);
        studentInfos = DataDao.queryStuCode(idinfo);

        if (idinfo.isEmpty()){
            Toast.makeText(this, "请输入考号或者身份证", Toast.LENGTH_SHORT).show();

        }else if (studentInfos.size() < 1 && studentInfoss.size() < 1 ){
            Toast.makeText(this, "输入错误", Toast.LENGTH_SHORT).show();
        }else {
            Intent intent = new Intent(this, MainCheckActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("Idcard", idinfo);
            intent.putExtras(bundle);
            startActivity(intent);
            finish();
        }


    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_INFO:
                    Toast.makeText(TransitionActivity.this, (String) msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MSG_CARD_INFO:
                    //获取身份证信息 并跳转
                    IDCard idCard = (IDCard) msg.obj;
                    Intent intent = new Intent(TransitionActivity.this,MainCheckActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("idcardinfo",idCard.getNumber());
                    byte[] fpbytes =  idCard.getFingerprint();
                    //将指纹信息传出
                    bundle.putSerializable("fpinfo",fpbytes);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                    break;
                case MSG_SHOW_PROGRESS_DIALOG: {
                    String[] info = (String[]) msg.obj;
                    mProgressDialog.setTitle(info[0]);
                    mProgressDialog.setMessage(info[1]);
                    mProgressDialog.show();
                    break;
                }
                case MSG_DISMISS_PROGRESS_DIALOG: {
                    mProgressDialog.dismiss();
                    break;
                }
                case  MSG_FACE_RESULT:{
                    //人脸比对 结果
                    String res = (String) msg.obj;
                    float score = Float.valueOf(res);
                    if(score == -1){
                        Toast.makeText(TransitionActivity.this, "比对失败", Toast.LENGTH_SHORT).show();
                    }else if(score == 0){
                        Toast.makeText(TransitionActivity.this, "比对失败", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(TransitionActivity.this, "比对成功", Toast.LENGTH_SHORT).show();
                        Intent faceIntent = new Intent(TransitionActivity.this,MainCheckActivity.class);
                        //将身份证号传递出去
                        //不能传BItmap对象  只能转成字节进行传递 否则跳转不成功
                        faceIntent.putExtra("snapshotFeature",snapshotFeature);
                        faceIntent.putExtra("stuCode",stuCode);
                        startActivity(faceIntent);

                    }
                    break;
                }


            }


        }

    };
}